package pe.edu.upla.lamerced.action;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import org.springframework.beans.factory.annotation.Autowired;

import pe.edu.upla.lamerced.bean.Habitacion;
import pe.edu.upla.lamerced.bean.Hospedaje;
import pe.edu.upla.lamerced.bean.Users;
import pe.edu.upla.lamerced.service.HabitacionService;
import pe.edu.upla.lamerced.service.HospedajeService;
import pe.edu.upla.lamerced.service.UsuarioService;
import pe.edu.upla.lamerced.utiles.Utiles;

public class HospedajeAction  extends DispatchAction {

	private static final Logger logger = Logger.getLogger(HospedajeAction.class);
	
	@Autowired
	HabitacionService habitacionService;
	@Autowired
	HospedajeService hospedajeService;
	@Autowired
	UsuarioService usuarioService;
	
	/**
	 * Lista de hospedajes actualmente activos que siguen en el hotel usando la habitacion
	 */
	public ActionForward listaHospedaje(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
			logger.debug(" consulta hospedaje de un cliente..... historico de hospedaje ");
			Users ulogin = Users.getUsuarioBean();
			if(ulogin.getTipo()==1){
	            request.setAttribute("lhospedajes", hospedajeService.listaHospedajes(""));					
			}
			if(ulogin.getTipo()==2){
				request.setAttribute("lhospedajes", hospedajeService.listaHospedajes(ulogin.getUsername()));
			}
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("consultasHome");
		}
		return mapping.findForward("lista");
	}	
	
	/**
	 * nuevo hospedaje en base a una reserva
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward preNuevoHospedaje(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" pre nuevo hospedaje");
            String cod = request.getParameter("cod");
            Hospedaje hos = hospedajeService.obtenerReserva(Integer.parseInt(cod));
            request.getSession().setAttribute("reserva",hos);
            
            DynaActionForm miform = (DynaActionForm)form;
            miform.set("cliente",hos.getUsersByIdUsuarioCli().getUsername());
            miform.set("idtipoHabitacion",hos.getHabitacion().getTipohabitacion().getIdtipoHabitacion().toString() );
            miform.set("idhabitacion", hos.getHabitacion().getIdhabitacion().toString());
            miform.set("diasreserva", hos.getDiasreserva().toString());
            miform.set("fecReserva", Utiles.dateToString(hos.getFecReserva(), "dd/MM/yyyy"));
            
            request.setAttribute("lstipohabitacion", habitacionService.listaTipoHabitacion());
			request.setAttribute("lsHabitacion", new ArrayList<Habitacion>());
			if(hos.getHabitacion().getTipohabitacion().getIdtipoHabitacion()!=null){
				Habitacion h = new Habitacion();
				h.setTipohabitacion(hos.getHabitacion().getTipohabitacion());
            	request.setAttribute("lsHabitacion", habitacionService.listaHabitaciones(h));
            }
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("procesosHome");
		}
		return mapping.findForward("nuevo");
	}	


	public ActionForward nuevoHospedaje(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug("registrando el nuevo hospedaje");
            DynaActionForm miform = (DynaActionForm)form;
            
			Hospedaje hos = (Hospedaje)request.getSession().getAttribute("reserva");
			hos.setFecAlquiler(Utiles.stringToDate(miform.getString("fecReserva"), Utiles.FORMATO_FECHA_CORTA));
			hos.setDiasreserva(Integer.parseInt(miform.getString("diasreserva")));
			Habitacion hab = habitacionService.obtenerHabitacion(Integer.parseInt(miform.getString("idhabitacion")));
			hab.setEstado(2);
			hos.setHabitacion(hab);
			hos.setEstado(2);
			Users ulogin = Users.getUsuarioBean();
			if(ulogin.getTipo()==1){
				Hospedaje reser = (Hospedaje) request.getSession().getAttribute("reserva");
				hos.setUsersByIdUsuarioCli(reser.getUsersByIdUsuarioCli());
				hos.setUsersByIdUsuarioEmp(ulogin);				
			}
			if(ulogin.getTipo()==2){
				hos.setUsersByIdUsuarioCli(ulogin);
				hos.setUsersByIdUsuarioEmp(usuarioService.obtenerUsuarioPorUsername("999999999"));	
			}
			hospedajeService.registrarHospedaje(hos);	
			hos = hospedajeService.obtenerHospedaje(hos.getIdhospedaje());			
			//ya no finalizo reserva porque la reserva a paADO A SER HOSPEDAJE
			//hospedajeService.finalizarreserva(((Hospedaje)request.getSession().getAttribute("reserva")));
            logger.debug(" hsoedaje RALIZADA");
            request.setAttribute("mensaje", "Hspedaje registrado");
            request.setAttribute("hdet", hos);
            request.getSession().removeAttribute("reserva");
		} catch (Exception e) {			
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("nuevo");
            //return preNuevoHospedaje(mapping, form, request, response);
		}
		return mapping.findForward("confirmar");
	}
	
	public ActionForward cancelNuevoHos(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" cancelar ");
            request.getSession().setAttribute("reserva",null);
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("procesosHome");
		}
		return mapping.findForward("nuevo");
	}
	/**
	 * nuevo hospedaje cuando el clietne no tenia reserva
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward preNuevoHospedaje2(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" pre nuevo hospedaje2");
            request.setAttribute("lstipohabitacion", habitacionService.listaTipoHabitacion());
			request.setAttribute("lsHabitacion", new ArrayList<Habitacion>());			
		} catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("procesosHome");
		}
		return mapping.findForward("nuevo2");
	}	
	public ActionForward nuevoHospedaje2(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug("registrando el nuevo hospedaje");
            DynaActionForm miform = (DynaActionForm)form;
			Hospedaje hos = new Hospedaje();
			hos.setFecAlquiler(Utiles.stringToDate(miform.getString("fecReserva"), Utiles.FORMATO_FECHA_CORTA));
			//hos.setDiasreserva(Integer.parseInt(miform.getString("diasreserva")));
			Habitacion hab = habitacionService.obtenerHabitacion(Integer.parseInt(miform.getString("idhabitacion")));
			hab.setEstado(2);
			hos.setHabitacion(hab);
			hos.setEstado(2);
			Users ulogin = Users.getUsuarioBean();
			if(ulogin.getTipo()==1){
				hos.setUsersByIdUsuarioCli(usuarioService.obtenerUsuario(Integer.parseInt(request.getParameter("cliente"))));
				hos.setUsersByIdUsuarioEmp(ulogin);				
			}
			hospedajeService.registrarHospedaje(hos);	
			hos = hospedajeService.obtenerHospedaje(hos.getIdhospedaje());			
			//hospedajeService.finalizarreserva(((Hospedaje)request.getSession().getAttribute("reserva")));
            logger.debug(" hospedaje registrado");
            request.setAttribute("mensaje", "Hspedaje registrado");
            request.setAttribute("hdet", hos);
            request.getSession().removeAttribute("reserva");
		} catch (Exception e) {			
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("nuevo");
            //return preNuevoHospedaje(mapping, form, request, response);
		}
		return mapping.findForward("confirmar");
	}
	
		
}
